const fa=require('fs');
const moment=require('moment');
const md5=require('md5');
const http=require('http');
const querystring=require('querystring');


module.exports = function(query) {
return new Promise((resolve, reject)=>{

//百度翻译接口参数
    params = {
                from: 'zh',
                to: 'en',
                query: query,
                appid:'20180109000113215',
                salt:moment.unix(),
                sign:md5(this.appid+this.query+this.salt+'KmDyCbTvnWa2J2r_VI5w')
    };

    var data = querystring.stringify(params);
    options = {
        host: 'fanyi.baidu.com',
        port: 80,
        path: '/v2transapi',
        method: 'POST',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            'Content-Length': data.length
        }
    };

    var req = http.request(options, function(res) {
        var result = '';

        res.setEncoding('utf8');
        res.on('data', function(data) {
            result += data;
        });
        // res.on('end', function() {
        //     var obj = JSON.parse(result),
        //         str = obj.trans_result.data[0].dst;
        //
        //     resolve(str);
        // });
    });

    req.on('error', function(err) {
        console.log(err);
        setTimeout(function() {
            translation(query, callback);
        }, 3000);
    });

    req.write(data);
    req.end();
})

};

